package com.xd.common.ascept;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xd.common.constant.SysConstant;
import com.xd.common.util.SecurityUtil;
import com.xd.core.company.entity.Company;
import com.xd.core.system.entity.*;
import com.xd.core.system.vo.PageVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.*;

@Aspect
@Slf4j
@Component
@Order(1)
public class WorkLogAscept {

    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void controllerAspect() {
    }

    /**
     * 返回两个对象不同的属性值
     * obj1 修改前
     * obj2 修改后
     */

    @Before("controllerAspect()")
    public void beforeMethod(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Object[] args = joinPoint.getArgs();
        ApiOperation workLog = method.getAnnotation(ApiOperation.class);
        String mkmc = workLog.value();
        String notes = workLog.notes();
        LoginUser user = SecurityUtil.getLoginUser0();
        String str = "";
        if (null != user) {
            SysUser sysUser = user.getUser();
            Company company = user.getCompany();
            if (sysUser.getCompanyType().equals(SysConstant.USER_COMPANY_TYPE_ONE))
                company.setCompanyName("平台");
            SysRole role = user.getRole();
            str = (null == company ? "" : company.getCompanyName() + ",") + role.getName() +
                    ":" + sysUser.getUserName() + " ";
        }
        if (notes.isEmpty())
            log.info(str + "执行" + mkmc + ",入参:" + Arrays.toString(args));
    }

    @AfterReturning(
            pointcut = "controllerAspect()",
            returning = "result"
    )
    public void returnMethod(JoinPoint joinPoint, Object result) throws JsonProcessingException {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        ApiOperation workLog = method.getAnnotation(ApiOperation.class);
        String mkmc = workLog.value();
        String notes = workLog.notes();
        if (method.getReturnType().equals(Void.TYPE)) {
            result = "void";
        } else {
            if (result instanceof PageVo || result instanceof List)
                result = "略";
            else {
                result = new ObjectMapper().writeValueAsString(result);
            }
        }
        if (notes.isEmpty())
            log.info(mkmc + "，响应:" + result);
    }

}
